<template>
  <div class="teacher-management">
    <!-- 页面标题 -->
    <div class="page-title">
      <h1>教师信息管理</h1>
    </div>

    <!-- 搜索条件 -->
    <div class="search-conditions">
      <el-form :model="searchForm" class="search-form">
        <!-- 第一行：搜索字段 -->
        <div class="search-fields">
          <el-form-item label="工号">
            <el-input
              v-model="searchForm.teacherId"
              placeholder="请输入工号"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入姓名"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="职称">
            <el-select
              v-model="searchForm.title"
              placeholder="请选择职称"
              clearable
              style="width: 150px"
            >
              <el-option label="教授" value="PROFESSOR" />
              <el-option label="副教授" value="ASSOCIATE_PROFESSOR" />
              <el-option label="讲师" value="LECTURER" />
              <el-option label="助教" value="ASSISTANT" />
            </el-select>
          </el-form-item>
          <el-form-item label="学院">
            <el-input
              v-model="searchForm.department"
              placeholder="请输入学院"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="在职" value="ACTIVE" />
              <el-option label="离职" value="INACTIVE" />
            </el-select>
          </el-form-item>
        </div>
        <!-- 第二行：操作按钮 -->
        <div class="search-actions">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button 
        v-if="canCreate('teacher-management')" 
        type="primary" 
        @click="handleAdd"
      >
        <el-icon><Plus /></el-icon>
        新增教师
      </el-button>
      <!-- 批量删除功能已屏蔽 -->
      <!-- <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button> -->
    </div>

    <!-- 教师信息列表 -->
    <div class="teacher-list">
      <el-table
        :data="teacherList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="teacherId" label="工号" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="gender" label="性别" min-width="80" />
        <el-table-column prop="title" label="职称" min-width="120">
          <template #default="{ row }">
            {{ getTitleText(row.title) }}
          </template>
        </el-table-column>
        <el-table-column prop="department" label="学院" min-width="150" />
        <el-table-column prop="phone" label="电话" min-width="130" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '在职' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="canEdit('teacher-management')" 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="canDelete('teacher-management')" 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <span class="total-info">共{{ pagination.total }}条记录</span>
      </div>
    </div>

    <!-- 添加/编辑教师对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="isEdit ? '编辑教师' : '添加教师'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="teacherFormRef"
        :model="teacherForm"
        :rules="teacherRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="teacherForm.name" placeholder="请输入教师姓名" />
        </el-form-item>
        <el-form-item label="工号" prop="employeeId">
          <el-input v-model="teacherForm.employeeId" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="teacherForm.gender" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="院系" prop="department">
          <el-input v-model="teacherForm.department" placeholder="请输入院系" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-select v-model="teacherForm.title" placeholder="请选择职称" style="width: 100%">
            <el-option label="教授" value="PROFESSOR" />
            <el-option label="副教授" value="ASSOCIATE_PROFESSOR" />
            <el-option label="讲师" value="LECTURER" />
            <el-option label="助教" value="ASSISTANT" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="teacherForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="teacherForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="在职" value="ACTIVE" />
            <el-option label="离职" value="INACTIVE" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Delete } from '@element-plus/icons-vue'
import { getTeacherList, addTeacher, updateTeacher, deleteTeacher } from '@/api/teacher'
import { canCreate, canEdit, canDelete } from '@/utils/permission'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showAddDialog = ref(false)
const isEdit = ref(false)
const teacherFormRef = ref()
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  teacherId: '',
  name: '',
  title: '',
  department: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 教师列表
const teacherList = ref([])

// 教师表单
const teacherForm = reactive({
  id: null,
  name: '',
  employeeId: '',
  gender: '',
  birthDate: '',
  department: '',
  title: '',
  phone: '',
  email: '',
  status: 'ACTIVE'
})

// 表单验证规则
const teacherRules = {
  name: [
    { required: true, message: '请输入教师姓名', trigger: 'blur' }
  ],
  employeeId: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入院系', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 获取教师列表
const getTeacherListData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1, // 后端从0开始
      size: pagination.pageSize,
      name: searchForm.name || undefined,
      title: searchForm.title || undefined,
      department: searchForm.department || undefined,
      employeeId: searchForm.teacherId || undefined,
      status: searchForm.status ? (searchForm.status === 'ACTIVE' ? '在职' : '离职') : undefined
    }
    
    const response = await getTeacherList(params)
    if (response.code === 200) {
      teacherList.value = response.data.content || []
      pagination.total = response.data.totalElements || 0
    } else {
      ElMessage.error(response.message || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
    ElMessage.error('获取教师列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTeacherListData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.currentPage = 1
  getTeacherListData()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getTeacherListData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getTeacherListData()
}

// 编辑教师
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(teacherForm, {
    id: row.teacherId,
    name: row.name,
    employeeId: row.teacherId,
    gender: row.gender || '',
    birthDate: row.hireDate,
    department: row.department,
    title: row.title,
    phone: row.phone,
    email: row.email,
    status: row.status === '在职' ? 'ACTIVE' : 'INACTIVE'
  })
  showAddDialog.value = true
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 删除教师
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除教师 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteTeacher(row.teacherId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getTeacherListData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除教师失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除功能已屏蔽
// const handleBatchDelete = async () => {
//   if (selectedRows.value.length === 0) {
//     ElMessage.warning('请选择要删除的数据')
//     return
//   }
//   
//   try {
//     await ElMessageBox.confirm(
//       `确定要删除选中的 ${selectedRows.value.length} 条数据吗？`,
//       '提示',
//       {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//     )
//     
//     // 模拟批量删除API调用
//     await new Promise(resolve => setTimeout(resolve, 500))
//     
//     ElMessage.success('批量删除成功')
//     getTeacherListData()
//     
//   } catch (error) {
//     // 用户取消
//   }
// }

// 提交表单
const handleSubmit = async () => {
  try {
    await teacherFormRef.value.validate()
    
    submitting.value = true
    
    const teacherData = {
      teacherId: teacherForm.employeeId,
      name: teacherForm.name,
      gender: teacherForm.gender,
      title: teacherForm.title,
      department: teacherForm.department,
      phone: teacherForm.phone,
      email: teacherForm.email,
      hireDate: teacherForm.birthDate || '2010-09-01', // 使用birthDate字段作为hireDate
      status: teacherForm.status === 'ACTIVE' ? '在职' : '离职'
    }
    
    let response
    if (isEdit.value) {
      response = await updateTeacher(teacherForm.id, teacherData)
    } else {
      response = await addTeacher(teacherData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      showAddDialog.value = false
      getTeacherListData()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 职称转换函数
const getTitleText = (title) => {
  const titleMap = {
    'PROFESSOR': '教授',
    'ASSOCIATE_PROFESSOR': '副教授', 
    'LECTURER': '讲师',
    'ASSISTANT': '助教'
  }
  return titleMap[title] || title
}

// 添加教师
const handleAdd = () => {
  resetForm()
  showAddDialog.value = true
}

// 重置表单
const resetForm = () => {
  isEdit.value = false
  Object.assign(teacherForm, {
    id: null,
    name: '',
    employeeId: '',
    gender: '',
    birthDate: '',
    department: '',
    title: '',
    phone: '',
    email: '',
    status: 'ACTIVE'
  })
  teacherFormRef.value?.resetFields()
}

// 组件挂载时获取数据
onMounted(() => {
  getTeacherListData()
})
</script>

<style lang="scss" scoped>
.teacher-management {
  .page-title {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }
  }
  
  .search-conditions {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .search-form {
      .search-fields {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        margin-bottom: 20px;
        
        .el-form-item {
          margin-bottom: 0;
          margin-right: 0;
        }
      }
      
      .search-actions {
        display: flex;
        justify-content: center;
        gap: 12px;
      }
    }
  }
  
  .action-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .teacher-list {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .el-table {
      margin-bottom: 16px;
      
      :deep(.el-table__header) {
        th {
          background: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      
      :deep(.el-table__row) {
        &:hover {
          background: #f8f9ff;
        }
      }
    }
    
    .pagination-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .total-info {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .teacher-management {
    .search-conditions {
      .search-form {
        .search-fields {
          flex-direction: column;
          gap: 12px;
          
          .el-form-item {
            margin-bottom: 0;
            margin-right: 0;
          }
        }
        
        .search-actions {
          margin-top: 16px;
        }
      }
    }
    
    .action-bar {
      flex-direction: column;
      
      .el-button {
        width: 100%;
      }
    }
    
    .teacher-list {
      padding: 16px;
      overflow-x: auto;
    }
  }
}
</style>
